<?php
class order extends shopAdminBase {
    /** @var  OrderMode */
    protected $orderMode;
    function __construct() {
        parent::__construct();
        $this->cms->setPageTitle("订单管理");
        $this->cms->setControlFile("shop/order/control.json");
        $this->orderMode=OrderMode::init();
    }

    function indexTask($page=1,$state=null,$id,$username,$serviceId){
        $this->cms->setActionTitle("所有订单");
        $shopId=$this->shopInfo['id'];
        $page=$page>=1? $page: 1;
        $countOfPage=15;
        $offset=($page-1)*$countOfPage;
        $result['serviceId']=$serviceId;
        $username=isset($username)?trim($username):null;
        if(isset($username)&!empty($username)){
            $user_id=UserMode::init()->getIdByUsername($username);
            $user_id=isset($user_id)?$user_id:-1;
        }else{
            $user_id=null;
        }
        list($result['service'],$service_total)=ServiceMode::init()->getList(2,100,0);
        usort($result['service'],function($a,$b){
            return ord(substr(iconv('utf-8', 'gbk', $a['service_name']), 0, 1))-
            ord(substr(iconv('utf-8', 'gbk', $b['service_name']), 0, 1));
        });
        if(isset($id)){
            $result['list'][0]=$this->orderMode->getDetailWithoutJoin($id);
            $total=!empty($result['list'])?1:0;
        }else{
            list($result['list'],$total)=$this->orderMode->getList($user_id,$shopId,$state,null,null,'normal',null,$serviceId,$countOfPage,$offset);
        }
        $result['list']=is_array($result['list'])?$result['list']:array();
        $service = ServiceMode::init();
        $user = UserModule::init('user');
        foreach($result['list'] as &$v){
            $order_info=$this->orderMode->getDetailWithoutJoin($v['id']);
            $service_info=$service->getDetail($v['service_id']);
            $v[$v['id']]['service_name']=$service_info['service_name'];
            $v[$v['id']]['service_address']=AddressMode::init()->getDetailAsString($service_info['address_id']);
            $user_info = $user->getDetail($v['user_id']);
            $v[$v['id']]['username']=$user_info['username'];
            $v[$v['id']]['userAddress']=AddressMode::init()->getUserAddressAsString($order_info['user_address_id']);
        }

        $url=WebRouter::init()->getQuestion("id={$id}&username={$username}&state={$state}&serviceId={$serviceId}&page=");
        $result['page']=new Page($page,$total,$countOfPage);
        $result['page']->setPageCallback(function($page)use($url){
            return $url.$page;
        });
        $result['currentState']=$state;
        $result['orderState']=array(
            'unpaid'=>"未付款",'unshipped'=>"未发货",'shipped'=>"已向服务站发货",'shipped_direct'=>"已向用户发货",
            'service'=>"等待服务站配送",'received'=>"用户已签收",'confirmed'=>"用户已确认",'refunding'=>"进入退货流程",
            'evaluate'=>"已评价");
        $this->cms->tableScene($result,"shop/order/order.php");
    }

    function serviceTask($page, $state=null){
        $this->cms->setActionTitle("服务订单");
        $shopId=$this->shopInfo['id'];
        $page=$page>=1? $page: 1;
        $countOfPage=15;
        $offset=($page-1)*$countOfPage;
        list($result['list'],$total)=$this->orderMode->getList(null,$shopId,$state,null,null,'service',null,null,$countOfPage,$offset);
        $url=WebRouter::init()->getQuestion("page=");
        $result['page']=new Page($page,$total,$countOfPage);
        $result['page']->setPageCallback(function($page)use($url){
            return $url.$page;
        });
        $result['currentState']=$state;
        $result['orderState']=array(
            'unpaid'=>"未付款",'evaluate'=>"已评价",'unused'=>"未使用",'used'=>"已使用");
        $this->cms->tableScene($result,"shop/order/service.php");
    }

    function detailTask($id){
        $shopId=$this->shopInfo['id'];
        $r=$this->orderMode->getDetail($id);
        if(empty($r)|| !$r['shop']['id']==$shopId) return new Intent(404,"未找到该订单");
        $r['service']=ServiceMode::init()->getDetail($r['order']['service_id']);
        if(!empty($r['order']['user_address_id'])){
            $r['userAddress']=AddressMode::init()->getUserAddressAsString($r['order']['user_address_id']);
        }
        $r['user_name']=UserMode::init()->getDetail($r['order']['user_id'])['real_name'];
        $r['user_phone']=UserModule::init('user')->getDetail($r['order']['user_id'])['username'];
        $r['buyer_name']=UserMode::init()->getDetail($r['order']['buyer_id'])['real_name'];
        $r['buyer_phone']=UserModule::init('user')->getDetail($r['order']['buyer_id'])['username'];
        $r['orderState']=array(
            'unpaid'=>"未付款",'unshipped'=>"未发货",'shipped'=>"已发货",'shipped_direct'=>"已向用户发货",
            'service'=>"等待服务站配送",'received'=>"用户已签收",'confirmed'=>"用户已确认",'refunding'=>"进入退货流程",
            'evaluate'=>"已评价",'unused'=>"未使用",'used'=>"已使用");
        $r['serviceAddress']=AddressMode::init()->getDetailAsString($r['service']['address_id']);
        $r['allocate']=MoneyMode::init()->getMoneyInfoByOrderId($id,'shopSell');
        $this->cms->tableScene($r,"shop/order/detail.php");
        return null;
    }

    // 一系列商家对订单的处理
    // 催促发货
    function dealUrgePayTask($order_id){
        $msgMode=MsgMode::init();
        $orderInfo=$this->orderMode->getDetail($order_id);
        $shopId=$this->shopInfo['id'];
        if(empty($orderInfo)|| $orderInfo['shop']['id']!=$shopId) return new Intent(404,"未找到该订单");
        $orderInfo['goods']=is_array($orderInfo['goods'])?$orderInfo['goods']:array();
        foreach($orderInfo['goods'] as $v){
            $msgMode->send($orderInfo['order']['user_id'],"{$orderInfo['shop']['company']}提醒您尽快给所购买商品付款",
                "{$orderInfo['shop']['company']}公司提醒您尽快给所购买的{$v['name']}商品付款，以免影响您购买本产品。",'shop');
        }
        $r['message']="提醒已经给用户发送";
        View::displayAsHtml($r,"plugin/state/tips.php");
    }
    // 订单关闭
    function dealCloseTask($order_id){
        if(OrderMode::init()->cancel($order_id)){
            $r['message']="取消订单成功";
        }else{
            $r['message']="取消订单失败";
        }
        $r['url']=WebRouter::init()->getPage('order','index');
        View::displayAsHtml($r,"plugin/state/tips.php");
    }
    // 发货处理
    function dealSendTask($order_id){
        $r['order_id']=$order_id;
        $r['order_info']=$this->orderMode->getDetail($order_id);
        $this->cms->formScene($r,"shop/order/dealSend.php");
    }
    function dealSendSubmitTask($order_id, $express_name, $express_num){
        $orderInfo=$this->orderMode->getDetail($order_id);
        $shopId=$this->shopInfo['id'];
        if(empty($orderInfo)|| $orderInfo['shop']['id']!=$shopId) return new Intent(404,"未找到该订单");
        if(!empty($orderInfo['order']['service_id'])){
            $type='shipped';
        }else{
            $type='shipped_direct';
        }
        if(isset($express_name)&&isset($express_num)){
            if(($this->orderMode->setExpress($order_id, $express_name, $express_num))&&($this->orderMode->setState($order_id,$type))){
                $r['message']="发货信息已记录";
            }else{
                $r['message']="发货失败，请重试！";
            }
        }else{
            if($this->orderMode->setState($order_id,$type)){
                $r['message']="发货信息已记录";
            }else{
                $r['message']="发货失败，请重试！";
            }
        }
        $r['url']=WebRouter::init()->getPage('order','index');
        View::displayAsHtml($r,"plugin/state/tips.php");
    }
    // 提醒服务站有商品
    function dealTipServiceTask($order_id){
        $msgMode=MsgMode::init();
        $orderInfo=$this->orderMode->getDetail($order_id);
        $shopId=$this->shopInfo['id'];
        if(empty($orderInfo)|| $orderInfo['shop']['id']!=$shopId) return new Intent(404,"未找到该订单");

        $serviceUserId=ServiceMode::init()->getUserId($orderInfo['order']['service_id']);
        if(!empty($serviceUserId)){
            $msgMode->send($serviceUserId,"{$orderInfo['shop']['company']}提醒您有一份商品发向您的服务站",
                "{$orderInfo['shop']['company']}提醒您有一份商品发向您的服务站，请您注意查收");
            $r['message']="提醒已经给服务站发送";
        }else{
            $r['message']="发送失败";
        }
        View::displayAsHtml($r,"plugin/state/tips.php");
    }
    // 提醒服务站尽快配送
    function dealUrgeServiceTask($order_id){
        $msgMode=MsgMode::init();
        $orderInfo=$this->orderMode->getDetail($order_id);
        $shopId=$this->shopInfo['id'];
        if(empty($orderInfo)|| $orderInfo['shop']['id']!=$shopId) return new Intent(404,"未找到该订单");

        $serviceUserId=ServiceMode::init()->getUserId($orderInfo['order']['service_id']);
        if(!empty($serviceUserId)){
            foreach($orderInfo['goods'] as $v) {
                $msgMode->send($serviceUserId, "{$orderInfo['shop']['company']}提醒您尽快发货",
                    "{$orderInfo['shop']['company']}提醒您,有一份商品还滞留在您的服务站，订单号{$order_id},商品名{$v['name']},请您尽快发货，以便您的客户得到更好的服务。");
            }
            $r['message']="提醒已经给服务站发送";
        }else{
            $r['message']="发送失败";
        }
        View::displayAsHtml($r,"plugin/state/tips.php");
    }
    // 服务订单使用
    function serviceCheckTask(){
        $this->cms->formScene(array(),"shop/order/serviceCheck.php");
    }
    function serviceCheckSubmitTask($service_code){
        $order_id=$this->orderMode->getOrderIdByCode($service_code);
        $orderInfo=$this->orderMode->getDetail($order_id);
        $shopId=$this->shopInfo['id'];
        if(empty($orderInfo)|| $orderInfo['shop']['id']!=$shopId) return new Intent(404,"未找到该订单");

        $userInfo=UserModule::init('user')->getDetail($orderInfo['order']['user_id']);
        $r['id']=$order_id;
        $r['shop']=$orderInfo['shop']['company'];
        $r['user']=$userInfo['username'];
        $r['code']=$service_code;
        $this->cms->tableScene($r,"shop/order/serviceCheckConfirm.php");
    }
    function serviceCheckConfirmTask($code){
        $order_id=$this->orderMode->getOrderIdByCode($code);
        $orderInfo=$this->orderMode->getDetail($order_id);
        $shopId=$this->shopInfo['id'];
        if(empty($orderInfo)|| $orderInfo['shop']['id']!=$shopId) return new Intent(404,"未找到该订单");

        $this->orderMode->setState($order_id, 'used');
        $r['message']="验证并使用成功";
        $r['url']=WebRouter::init()->getPage('order','service');
        View::displayAsHtml($r,"plugin/state/tips.php");
    }
}